package com.albert.tool;

import android.util.Log;

import com.albert.HttpUtils.HttpUtils;
import com.albert.model.NetConfigModel;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Map;

public class NetConfigManager {

    private static NetConfigModel config;
    private static final ObjectMapper mapper = new ObjectMapper();

    private NetConfigManager() {
    }

    /**
     * 异步初始化配置
     *
     * @param url      请求地址
     * @param callback 初始化结果回调
     */
    public static void initWithServer(String url, InitCallback callback) {

        Map<String, Object> requestData = new HashMap<>();
        requestData.put("deviceType", DevBoard.DeviceType.DEVICE_TYPE_PHONE.deviceType);

        ObjectMapper mapper = new ObjectMapper();
        String jsonBody;
        try {
            jsonBody = mapper.writeValueAsString(requestData);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        HttpUtils.post(url, jsonBody, new HttpUtils.HttpCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    if (JsonUtils.isJsonString(response)) {
                        config = JsonUtils.fromJson(response, NetConfigModel.class);
                        if (callback != null) {
                            Log.d("POST_Success: ", config.toString());
                            callback.onSuccess(config);
                        }
                    } else {
                        if (callback != null) {
                            callback.onFailure(new Exception("返回的不是合法 JSON"));
                        }
                    }
                } catch (Exception e) {
                    if (callback != null) {
                        callback.onFailure(e);
                    }
                }
            }

            @Override
            public void onFailure(Exception e) {
                e.printStackTrace();
                Log.d("POST failed: ", e.getLocalizedMessage());
                if (callback != null) {
                    callback.onFailure(e);
                }
            }
        });
    }

    /**
     * 获取全局配置
     */
    public static NetConfigModel getConfig() {
        if (config == null) {
            config = new NetConfigModel();
        }
        return config;
    }

    /**
     * 清空配置
     */
    public static void clear() {
        config = null;
    }

    // 初始化回调接口
    public interface InitCallback {
        void onSuccess(NetConfigModel model);

        void onFailure(Exception e);
    }
}
